import { Form, Icon, Input, Button, message } from 'antd';
import React, { Component } from 'react';
import './login.css';
import cookie from 'react-cookies';

const FormItem = Form.Item;

const URL_LOGIN = "http://10.254.251.233/api/xsse/userLogin.json";

class LoginForm extends Component {
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
                let requestData = this.toFormatFormData(values);
                this.toFetch(URL_LOGIN, requestData);
            }
        });
    }


    componentWillUnmount() {
        cookie.remove('stg_user');
    }

    /**
     * 向服务器发送请求
     * @param {url} url 
     * @param {请求数据 ip,mac,token} data 
     */
    toFetch = (url, data) => {
        console.log("开始发送登录请求，登录url=" + url + data);
        fetch(url + data, {
            method: "GET", // *GET, POST, PUT, DELETE, etc.
            mode: "cors", // no-cors, cors, *same-origin
            cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
            credentials: "same-origin", // include, *same-origin, omit
            headers: {
                "Content-Type": "application/json; charset=utf-8",
            },
            redirect: "follow", // manual, *follow, error
            referrer: "no-referrer", // no-referrer, *client
        })
            .then(response => response.json()).then(
                resJson => {
                    if (resJson.ret_code === 0) {
                        console.log("登录成功！登录返回信息：" + JSON.stringify(resJson));
                        this.loginOk(resJson);
                    } else {
                        console.log("登录失败！登录返回信息：" + JSON.stringify(resJson));
                        this.loginFaild(resJson);
                    }
                }) // JSON-string from `response.json()` call
            .catch(error => {
                console.error(error)
                message.error("登录失败：" + error);
            }); // parses response to JSON
    }

    /**登录成功 */
    loginOk = (data) => {
        //添加cookies
        this.addCookies(data);
        //跳转到策略界面
        this.props.history.push("../strategyInfo/index.js");

        message.success("登录成功");
    }

    /**登录失败 */
    loginFaild = (data) => {
        message.error("登录失败：" + data.ret_msg);
    }

    /**添加cookies */
    addCookies = (data) => {
        const expires = new Date()
        expires.setDate(expires.getDate() + 14)

        cookie.save(
            'stg_user',
            data,
            {
                path: '/',
                expires,
                maxAge: 1000 * 60 * 60 * 24,
                domain: 'https://play.bukinoshita.io',
                secure: true,
                httpOnly: true
            }
        )
    }

    /**
     * 格式化表单数据
     * @param {*} e 
     */
    toFormatFormData = (formData) => {
        return "?ip=" + formData.ip + "&mac=" + formData.ip + "&token=" + formData.token;
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form onSubmit={this.handleSubmit} className="login">
                <FormItem>
                    <div className="login-top">XSSE</div>
                </FormItem>
                <FormItem className="login-center-input">
                    {getFieldDecorator('ip', {
                        rules: [{ required: true, message: '请输入IP' }],
                    })(
                        <Input prefix={<Icon type="environment" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="IP" />
                    )}
                </FormItem>
                <FormItem className="login-center-input">
                    {getFieldDecorator('port', {
                        rules: [{ required: true, message: '请输入端口号' }],
                    })(
                        <Input prefix={<Icon type="inbox" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="端口号" />
                    )}
                </FormItem>
                <FormItem className="login-center-input">
                    {getFieldDecorator('username', {
                        rules: [{ required: true, message: '请输入用户名' }],
                        initialValue: 'qts',
                    })(
                        <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="用户名" />
                    )}
                </FormItem>
                <FormItem className="login-center-input">
                    {getFieldDecorator('token', {
                        rules: [{ required: true, message: '请输入TOKEN' }],
                    })(
                        <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="TOKEN" />
                    )}
                </FormItem>
                <FormItem>
                    <Button type="primary" htmlType="submit" className="login-form-button">登录</Button>
                </FormItem>
            </Form>
        );
    }
}

const LoginPage = Form.create()(LoginForm);


export default LoginPage;